package leetcode;

import java.util.*;
import java.util.stream.Collectors;

public class LCR129 {


    public static void main(String[] args) {
      char[][]  grid = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
      wordPuzzle(grid,"SEE");
    }

    public static boolean wordPuzzle(char[][] grid, String target) {

        HashMap<String,Integer> mapping = new LinkedHashMap<>();
        List<String> inner = new ArrayList<>();

        for (int n = 0; n <target.length() ; n++) {
            char c = target.charAt(n);
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (c == grid[i][j]) {
                        Integer orDefault = mapping.getOrDefault(n + "," + c, 0);
                        mapping.put(n+","+c,orDefault + 1);
                        inner.add(n+","+c + "|" + i + "," + j);
                    }
                }
            }
        }
//        System.out.println(mapping);
//        return false;

        //按顺序遍历map的key，从list里边找出包含这个key的值，找到了起点
        //遍历起点，找到其相邻的四个坐标位置
        //判断下个字符的坐标是否在这四个点上
        Set<String> strings = mapping.keySet();


        ArrayList<String> stringsOrder = new ArrayList<>(strings);
        for (int i = 0; i < strings.size(); i++) {
            if(i == stringsOrder.size() - 1){
                break;
            }
            String itemKey = stringsOrder.get(i);
            List<String> collect = inner.stream().filter(s -> s.contains(itemKey)).collect(Collectors.toList());
            for (String s : collect) {
                List<String> nearList = new ArrayList<>();
                //计算可能的四个坐标
                String[] splitL = s.split("\\|");
                String[] split = splitL[1].split(",");
                int x = Integer.parseInt(split[0]);
                int y = Integer.parseInt(split[1]);
                String left = (x-1) + "," + y;
                String right = (x+1) + "," + y;
                String below = x + "," + (y -1) ;
                String top = x + "," + (y +1) ;
                nearList.add(left);
                nearList.add(right);
                nearList.add(below);
                nearList.add(top);

                int sum = 0;
                //下一值的坐标,计算map之前的序列之和
                Integer next = mapping.get(stringsOrder.get(i + 1));
                for (int j = 0; j <= i; j++) {
                    sum = sum + mapping.get(stringsOrder.get(j));
                }
                int all = sum + next;
                List<String> nextZBs = inner.subList(sum, all).stream().map(on -> on.split("\\|")[1]).collect(Collectors.toList());

                List<String> nearZb = nearList.stream().filter(in -> nextZBs.contains(in)).collect(Collectors.toList());
                System.out.println(nearZb);
            }
        }

        return false;
    }
}
